package com.drondea.testclient.panel;

import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import com.drondea.sms.conf.sgip.SgipClientSocketConfig;
import com.drondea.sms.session.sgip.SgipClientSessionManager;
import com.drondea.testclient.handler.sgip.SgipClientCustomHandler;
import com.drondea.testclient.handler.sgip.server.SgipServer;
import com.drondea.testclient.model.AppConfig;
import com.drondea.testclient.model.Model;
import com.drondea.testclient.model.User;
import com.drondea.testclient.service.AbstractTcpService;
import com.drondea.testclient.service.ConfigService;
import com.drondea.testclient.service.SgipService;
import com.drondea.testclient.service.provider.SgipClientMessageProvider;
import com.drondea.testclient.util.CommonThreadPoolFactory;
import com.drondea.testclient.util.ProtocolType;
import com.drondea.testclient.util.counter.SgipAtomicUtil;
import com.drondea.testclient.util.counter.SmppAtomicUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;


/**
 * SGIP协议面板
 *
 * @author shd
 */

@Slf4j
public class SgipPanel extends AbstractTcpPanel {

    private static final SgipPanel SGIP_PANEL = new SgipPanel();

    private SgipPanel() {
    }

    public static SgipPanel getInstance() {
        return SGIP_PANEL;
    }

    @Override
    public void init(int width, int height) {
        user = ConfigService.findBean(Model.CT_USER.getCode(), "SGIP", User.class);
        log.info("sgip user : {}", user);

        CronUtil.schedule("0/1 * * * * ? ", (Runnable) () -> {
            long nowSendCount = SgipAtomicUtil.SEND_COUNT.get();
            submitSpeedLabel.setText(StrUtil.format("发送速度: {}/s", (nowSendCount - lastSendCount)));
            lastSendCount = nowSendCount;
            long nowResponseCount = SmppAtomicUtil.RESPONSE_COUNT.get();
            responseSpeedLabel.setText(StrUtil.format("响应速度: {}/s", (nowResponseCount - lastResponseCount)));
            lastResponseCount = nowResponseCount;
            long nowReportCount = SgipAtomicUtil.REPORT_COUNT.get();
            reportSpeedLabel.setText(StrUtil.format("回执速度: {}/s", (nowReportCount - lastReportCount)));
            lastReportCount = nowReportCount;
        });

        AppConfig appConfig = ConfigService.findBean(Model.APP_CONFIG.getCode(), "APP", AppConfig.class);
        if (appConfig.isStartSgipServer()) {
            int port = appConfig.getSgipPort();
            if (port == 0) {
                port = user.getPort();
            }
            if (port > 0) {
                SgipServer.getInstance().start(port);
            }
        }
        super.init(width, height);
    }

    @Override
    protected void connect() {
        // 保存连接的配置信息
        saveConfigInfo();

        isCanSend = true;

        SgipClientSocketConfig socketConfig = new SgipClientSocketConfig(userNameTextField.getText(),
                10 * 1000, 16, ipTextField.getText(), Integer.parseInt(portTextField.getText()));
        socketConfig.setChannelSize(Integer.parseInt(connectCountTextField.getText()));
        socketConfig.setNodeId(3027130067L);
        socketConfig.setUserName(userNameTextField.getText());
        socketConfig.setPassword(passwordTextField.getText());

        //限速 条/s
        socketConfig.setQpsLimit(Integer.parseInt(speedTextField.getText()));
        //开启超时监控,设置监控间隔时间，这个值最好是RequestExpiryTimeout的1/2
        socketConfig.setWindowMonitorInterval(10 * 1000);
        //设置响应超时时间
        socketConfig.setRequestExpiryTimeout(20 * 1000);
        AppConfig appConfig = ConfigService.findBean(Model.APP_CONFIG.getCode(), "APP", AppConfig.class);
        socketConfig.setWindowSize(appConfig.getWindowSize() == 0 ? 10000 : appConfig.getWindowSize());
        log.info("sgip window size : {}", socketConfig.getWindowSize());

        SgipClientCustomHandler sgipCustomHandler = new SgipClientCustomHandler();
        sessionManager = new SgipClientSessionManager(socketConfig, sgipCustomHandler);
        sessionManager.setMessageProvider(new SgipClientMessageProvider());
        //创建链接
        sessionManager.doOpen();
        sessionManager.doCheckSessions();
    }

    @Override
    public ProtocolType getProtocol() {
        return ProtocolType.SGIP;
    }

    @Override
    protected AbstractTcpService getService() {
        return SgipService.getInstance();
    }

    @Override
    protected void counterReset() {
        SgipAtomicUtil.clear();
    }

    @Override
    protected void loopRefreshPanelData(int delay) {
        CommonThreadPoolFactory.getInstance().getScheduleExecutor().schedule(() -> {
            sendCountLabel.setText(StrUtil.format("发送数量: {}", SgipAtomicUtil.SEND_COUNT.get()));
            
            loopRefreshPanelData(delay);
        }, delay, TimeUnit.MILLISECONDS);
    }
    
    @Override
    protected void saveConfigInfo() {
        User user = new User("SGIP", ipTextField.getText(), Integer.parseInt(portTextField.getText()), userNameTextField.getText(),
                passwordTextField.getText(), Integer.parseInt(connectCountTextField.getText()), Integer.parseInt(speedTextField.getText()));
        ConfigService.update(Model.CT_USER.getCode(), "SGIP", user);
    }


}